package org.yoao.crm.business.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.yoao.crm.bean.Role;
import org.yoao.crm.bean.StaticBean;
import org.yoao.crm.business.service.IRoleService;
import org.yoao.crm.dao.RoleDAO;
import org.yoao.crm.struts.form.RoleForm;

/**
 * @author yxwonline.com
 * @description
 * @date 2010-7-31 下午01:31:19
 */
public class RoleServiceImpl implements IRoleService {
	private RoleDAO roleDAO = new RoleDAO();

	@Override
	public List view(int startRow, int endRow, Map map) throws Exception {
		return roleDAO.find(startRow, endRow, map);
	}

	@Override
	public List getRoles() throws Exception {
		return roleDAO.findAll();
	}

	@Override
	public int getDataCount(Map map) throws Exception {
		return roleDAO.getDataCount(map);
	}

	@Override
	public RoleForm add(RoleForm form) throws Exception {
		Role role = new Role();
		BeanUtils.copyProperties(role, form);
		Role tmp = roleDAO.findRoleByRoleId(role.getRoleId());
		if(tmp != null){
			form.setInfo("角色已存在,重复!");
		}else{
			int result = roleDAO.insert(role);
			if(result > -1){
				Role tmp2 = roleDAO.findRoleByRoleId(role.getParentId());
				form.setId(result);
				form.setInfo("数据保存成功.");
			}else form.setInfo("数据保存失败.");
		}
		return form;
	}

	@Override
	public void delete(String id) throws Exception {
		String[] idArr = id.split(",");
		if(idArr != null && idArr.length > 0){
			for(int i=0;i<idArr.length;i++){
				Role role = roleDAO.findChildById(idArr[i]);
				if(role != null)
					delete(String.valueOf(role.getId()));
				roleDAO.delete(idArr[i]);
			}
		}
	}

	@Override
	public RoleForm getRole(String id) throws Exception {
		RoleForm form = new RoleForm();
		Role role = roleDAO.findById(id);
		if(role != null) BeanUtils.copyProperties(form, role);

//		if(StaticBean.ROLE_SYSTEM.equals(role.getParentId()))
//			form.setParentId("系统管理员");
//		else{
//			Role tmp = roleDAO.findRoleByRoleId(role.getParentId());
//			form.setParentId(tmp.getRoleName());
//		}

		return form;
	}

	@Override
	public RoleForm modify(RoleForm form) throws Exception {
		Role role = new Role();
		BeanUtils.copyProperties(role, form);
		if(roleDAO.modify(role) > -1){
			Role tmp = roleDAO.findParentByRoleId(role.getRoleId());
			form.setInfo("数据保存成功.");
		}else  form.setInfo("数据保存失败.");
		return form;
	}

	@Override
	public List getAllChildRole(String currRoleId) throws Exception {
		return roleDAO.findAllChilds(currRoleId);
	}

	/***
	 * 判断用户是否还有子角色
	 */
	public boolean isHaveChildRole(String roleId) throws Exception {
		List list = roleDAO.findChildByParentID(roleId);
		if(list != null) return true;
		else return false;
	}

	@Override
	public String getAllParentRole(String currRoleId) throws Exception {
		return roleDAO.findAllParentID(currRoleId);
	}
}